'use strict';

app.controller('homeCtrl', ['$scope','$http','loginService', function($scope,$http,loginService){
	$scope.txt='Page Home';
	loginService.islogged(); 
	$scope.link = loginService.getLink();
	 $scope.menu= [{link: "User management",href: "#/user"},
                  {link: "Group management",href: "#/group"},
                  {link: "Event management",href: "#/event"},
                  {link: "Social management",href: "#/home"},
                  {link: "Interest management",href: "#/interest"},
				  {link: "Map",href: "#/map"},
                  {link: "Statistic",href: "#/statistic"},
				  {link: "Admin",href: "#/admin"}
                  ];
	if(!loginService.verify_admin())
	   $scope.menu.splice(6, 1);
	//var uid = loginService.getUser(); 
	//alert(uid.role);
	
	$scope.logout=function(){ 
		loginService.logout();
	}
	
	
	
	$scope.init = function() {
    	 loginService.islogged(); 
    	// $scope.getUserById($scope.user_id);
    	 $scope.list_user(0,1);
    	
    };
    
    $scope.show_login = true;
	$scope.show_home = false;
//	/ Session.updateSession();
		$scope.$watch('show_home', function(Session) {   
			
			//alert(Session);
		}); 
	 
	 
    //=====================paging groups of user======================
    $scope.entryLimit_group = 5
    $scope.offset_group = 0;
    $scope.disablePrev_group = true;
    $scope.disableNext_group = false;
    $scope.page_now_group = 1;
    //================================================================
    
    
    $scope.currentPage = 1; //current page
    $scope.entryLimit = 10; //max rows for data table
    $scope.maxSize = 5; //pagination max size
   
    $scope.page_now = 1;
    
    
    //$scope.entryLimit = 3;
    $scope.offset = 0;
    $scope.disablePrev = true;
    $scope.disableNext = false;
    $scope.personFilter = {};
    $scope.user= {
    	      username: "",
    	      password: "",
    	      fullName: function() {
    	         var userObject;
    	         userObject = $scope.user;
    	         return userObject.username + " " + userObject.password;
    	      }
    	   };
    
 
    
    
	 $scope.lock = function(userid,id){
		  if(id==0){
			
			
				  $http.get($scope.link+'user_bl/'+userid).success(function(data){
			        	console.log('user is locked');
			        	//$scope.lock = data;
			         	//$scope.list_user($scope.offset,$scope.page_now);
			         }).error(function(data, status, config) {
			        	console.log('can not lock user with id : ' + userid);
			       });
			 
		  }
		  else if(id==1){
			  $http.get($scope.link+'user_ubl/'+userid).success(function(data){
		        	console.log('user is unlocked');
		        	$scope.unlock = data;
		        	//alert('unlock :   '  +  JSON.stringify(data));
		        	//$scope.getGroupsByUserId(data.data.id);
		        	 $scope.list_user($scope.offset,$scope.page_now);
		         }).error(function(data, status, config) {
		        	console.log('can not un lock user with id : ' + userid);
		       });  
		  }
		  
		  $scope.getUserById(userid);
		  $scope.go(userid,0,1);  
		 
	 }
	
	
	
	 $scope.list_user = function(offset, page_now){
		
			$http.get($scope.link+'users').success(function(data,status, config){
				console.log('load list of user');
				$scope.model = data;
				$scope.jsonToArray(data);
				$scope.nb_row_notchange =  data.data.length;
				$scope.noOfPages = Math.ceil($scope.nb_row_notchange/$scope.entryLimit);
				$scope.offset = offset;
                $scope.currentPage = page_now;
				
			})
			.error(function(data, status, config) {
				console.log('can not load list of user');
		    }); 
	 }
	

	

	
	$scope.jsonToArray = function (data) {
		$scope.a = new Array();
		var i = 0;
		angular.forEach(data.data,function(){
			$scope.a[i]=new Array(7);
    		$scope.a[i][0] =  data.data[i].login_id;
			$scope.a[i][1] =  data.data[i].first_name;
			$scope.a[i][2] =  data.data[i].last_name;
			$scope.a[i][3] =  data.data[i].email;
			$scope.a[i][4] =  data.data[i].id;
			$scope.a[i][5] =  data.data[i].register_time;
			$scope.a[i][6] =  data.data[i].blocked_flg;
			$scope.a[i][7] =  data.data[i].searchable;
			$scope.a[i][8] =  data.data[i].privacy;
            i++;
        })
        $scope.nbr_rows = i ;
		
		$scope.a_ini= angular.copy($scope.a);
	}
	
	
//	 $scope.today = function(p, val) {
//		
//	    var today_datetime =  getdatetime_search(val); 
//	   //alert(p[5]  - today_datetime);
//	   return p[5] > today_datetime;
//	 }
	
//	 $scope.getdatetime_search =function(nb_day){
//		 var now = new Date();
//		 var today_datetime =  Math.floor(now.getTime());
//		 today_datetime -=(nb_day*86400000);
//		 return today_datetime;
//	 }
	 
	 
//	 $scope.setPage = function(pageNo) {  
//	        $scope.currentPage = pageNo;
//	    };
	 $scope.$watch('search1', function(term) {
	        $scope.filter1 = function() {  
	        //	alert($scope.filtered.length);
	            $scope.noOfPages = Math.ceil($scope.filtered.length/$scope.entryLimit);
	            
	           
	            if( !angular.isUndefined($scope.search1) ) {
	            	//$scope.recalculate_array($scope.filtered);
	            	//alert($scope.filtered);
	            	//pageResult($scope);
	            }else{
	            	//alert('empty');
	            	
	            }
	            
            
	        }
	    });
	 
		$scope.filter = function () {
			$scope.filtered_search = null;
			
		
			$scope.filtered_search = angular.copy($scope.filtered);
			
			if($scope.nb_row_notchange == $scope.filtered.length)
			   $scope.filtered_ini = angular.copy($scope.filtered);
		
			
			if( !angular.isUndefined($scope.search1) ) {
	        
				if( !angular.isUndefined($scope.filtered_ini) )  {
					$scope.recalculate_array($scope.filtered_ini);
					$scope.disablePrev = true;
				}
				$scope.filter_ini = $scope.filtered.length;
	          }
		}
	 
		$scope.$watch('b', function() {   
			if( ($scope.page_now_group==1)  &&  ($scope.nbr_rows_groups <= $scope.entryLimit_group) )
			 {
			 $scope.disableNext_group = true;
			 }
			
		}); 
		
		$scope.$watch('a', function() {   
			if( ($scope.page_now==1)  &&  ($scope.nbr_rows <= $scope.entryLimit) )
			 {
			 $scope.disableNext = true;
			 }
			
		});
		
		 $scope.$watch('filtered', function() {   
			 
			 if( !angular.isUndefined($scope.search1) ) { 
					$scope.filter_ini = $scope.filtered.length;
					//alert($scope.filtered.length);
				}
			  
			  if($scope.search1 ==''){  
					$scope.filter_ini = $scope.nb_row_notchange;
				}
			 
			 
			 if( ($scope.page_now==1)  &&  ($scope.filter_ini <= $scope.entryLimit) )
			 {  
				 if(!angular.isUndefined($scope.search1)){  //search has some thing
					    if(!$scope.click_prev)
					    	$scope.disableNext = true;
					}
			 }
			 else if(($scope.page_now==1) &&  ($scope.filter_ini > $scope.entryLimit)){
			 $scope.disableNext = false;
		    }
			 
			 
			 if( ($scope.page_now==$scope.noOfPages)  &&  ($scope.filter_ini <= $scope.entryLimit) )
	 			{
				    $scope.disablePrev = true;
	 			}
		     else if(($scope.page_now==$scope.noOfPages) &&  ($scope.filter_ini > $scope.entryLimit)){
					 $scope.disablePrev = false;
		     }
			 
			 
			 if(($scope.page_now!=1) && ($scope.page_now!=$scope.noOfPages)){
			     if ( $scope.filter_ini < $scope.entryLimit){   
					 $scope.disableNext = true;
                    // $scope.disablePrev = true;
				 }
				 else{
					 $scope.disableNext = false;
					 //$scope.disablePrev = false;
				 }
			 }
			
		 });
	 
	 $scope.recalculate_array = function (data) {
		 $scope.a = new Array();
		 var i = 0;
		 angular.forEach(data,function(){
			 $scope.a[i]=new Array(7);
			 var splitted =  ((data[i]).toString()).split(',') ;
		      $scope.a[i][0] =  splitted[0];
		      $scope.a[i][1] =  splitted[1];
			  $scope.a[i][2] =  splitted[2];
			  $scope.a[i][3] =  splitted[3];
			  $scope.a[i][4] =  splitted[4];
			  $scope.a[i][5] =  splitted[5];
			  $scope.a[i][6] =  splitted[6];
			  $scope.a[i][7] =  splitted[7];
			  $scope.a[i][8] =  splitted[8];
			 i++;

         })
         $scope.nbr_rows = i ;
		 //alert($scope.nbr_rows);
	 }
	 
//	 Math.floor(now.getTime())
//	 myDate=myDate.split("-");
//	 var newDate=myDate[1]+"/"+myDate[0]+"/"+myDate[2];
 
	 
	// switch to next page
	$scope.nextPage = function() { 
       nextPage_common($scope);
	}

	// switch to previous page
	$scope.previousPage = function() {
      previousPage_common($scope);
	}
	
    
	// switch to next page
	$scope.nextPage_group = function() { 
       nextPage_common_group($scope);
	}

	// switch to previous page
	$scope.previousPage_group = function() {
      previousPage_common_group($scope);
	}
	
	var show = 1;
	var show_list_user = 1;
	var show_group_detail = 0;
	$scope.go = function(user,id,type_return) {
		show = id;
		show_list_user = 0;
		show_group_detail=0;
	    $scope.getUserById(user);
	    $scope.type_return = type_return;
	    
	};
	

	
	$scope.return_ = function(user,id) {
		if ( $scope.type_return ==1){ 
		  show = 1;
		  show_list_user = 1;
	   	  $scope.list_user(0,1);
		}
		else if ( $scope.type_return ==2){
			show = 1;
			show_group_detail = 1;	
			$scope.type_return = 1;
		}
	};
	
	$scope.return_user_detail = function(user,id) {
		show = 0;
		show_list_user = 0;
		show_group_detail = 0;   //alert($scope.user_id);
		$scope.go($scope.user_id,0,1);
	};
	
	$scope.group_go = function(groupId, id,userId) {
		show = id;
		show_group_detail = 1;
	    $scope.getGroupByGroupId(groupId);
	    $scope.user_id = userId;
	};
	
	 $scope.is = function (id) {
	        return show == id;
	    };
	
	
	  $scope.group_detail_visible = function (id) {
	        return show_group_detail == id;
	  };   
	    
     $scope.list_user_visible = function (id) {
		    return show_list_user == id;
	 };   
	    
	 $scope.getUserById = function(id){
	        $http.get($scope.link+'users/'+id).success(function(data){
	        	console.log('user is loaded');
	        	$scope.user = data;
	        	$scope.getGroupsByUserId(data.data.id);
	        }).error(function(data, status, config) {
	        	console.log('can not load user with id : ' + id);
	 });
	 }
	
	 
	 $scope.getGroupsByUserId = function(id){
	        $http.get($scope.link+'groups/'+id).success(function(data){
	        	console.log('groups is loaded');
	        	$scope.groups = data;
	        	//$scope.getUsersByGroupId(id);
	        	 $scope.jsonToArray_groups(data);
	        	 pageResult_group($scope);
	        }).error(function(data, status, config) {
	        	console.log('can not load list of groups with user id : ' + id);
	 });
	 }
	
	 
	 $scope.jsonToArray_groups = function (data) {
			$scope.b = new Array();
			var i = 0;
			angular.forEach(data.data.groups_list,function(){
				$scope.b[i]=new Array(2);
	    		$scope.b[i][0] =  data.data.groups_list[i].name;
				$scope.b[i][1] =  data.data.groups_list[i].id;
	            i++;
	        })
	        $scope.nbr_rows_groups = i ;
			
			$scope.b_ini= angular.copy($scope.b);
		}
	 
	 
	 $scope.getUsersByGroupId = function(id){
	        $http.get($scope.link+'user_group/'+id).success(function(data){
	        	console.log('list users by group is loaded');
	        	$scope.nb_users = data.data.members_list.length;
	        	$scope.lst_user = data;
	        	
	        }).error(function(data, status, config) {
	        	console.log('can not load list of users by group Id : ' + id);
	 });
	 }
	 
	 
	 $scope.getGroupByGroupId = function(id){ 
	        $http.get($scope.link+'group/'+id).success(function(data){
	        	var loc = data.data.location;  //alert( data.data.privacy);
	        	var loc_Str = loc.toString();
	        	var arr  = loc_Str.split(",") ; 
	        	$scope.long = arr[0];
	        	$scope.lat = arr[1];
	        	console.log('a group is loaded');
	        	$scope.group = data;
	        	$scope.getUserById(data.data.owner_id);
	        	
	        	$scope.getUsersByGroupId(id);
	        }).error(function(data, status, config) {
	        	console.log('can not load group with group id : ' + id);
	 });
	 }
	 
	 
	 
	 $scope.filter_day = [{
	      "time_": "in 24 hours",
	    	  "val": 1
	    }, 
	    { "time_": "in 7 days",
	    	"val": 7
	    }, 
	    { "time_": "in 1 month",
	    	"val": 100
	    }];


	    $scope.personFilter = function (v) { 
	        return Object.keys($scope.search1 || {}).every(function (key) {
	        	//alert(JSON.stringify( v));
	        	
	        	
	        	var value = $scope.search.val;
	        	
	        	return  today(v,value);
	        });
	    };
	    
	 
	    $scope.login = function() {  
	    	
	       	
	      	var userObj = {
	       			username: $scope.user.username,
	       			password: $scope.user.password
	    		};
	      	
	      	alert(JSON.stringify(userObj));
	      	    var res = $http.post($scope.link+'login', userObj);
	        	 
	         	res.success(function(data, status, headers, config, Session) {
		        	if (data.data.username ==userObj.username){
		        	 $scope.show_login = false;
		        	 $scope.show_home  = true;
		        	
		        	 alert(JSON.stringify(Session));
		        	  }
	            
	          
	             });
	            res.error(function(data, status, headers, config) {
	            	 console.log('Wrong username or password');
	          	   
	            });	
	        	
	        };
	
	
	
}])